package prog.model;


import prog.Main;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import javax.swing.SwingUtilities;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MrKhoai
 */
public class ThreadWorker {
    private int view;
    private Data data = null;
    private Project project;

    public ThreadWorker(Project pj, int view) {
        this.view = view;
        this.project = pj;
    }
    public Thread createThread() {
        Thread t = new Thread(new Runnable() {
            public void run() {
                boolean flag = true;
                while(flag && project.getStatus() == Project.RUN) {
                    data = project.popFromStack();
                    if(data != null) {
                        try {
                            data.download(project.getDst());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if(project.stack.size() > 0)
                            flag = true;
                        else {
                            project.setStatus(Project.FINISHED);
                            flag = false;
//                            int count = 0;
//                            for(Thread t : project.thread) {
//                                System.out.println("alive");
//                                if(t.isAlive()) {
//                                    //System.out.println("alive");
//                                    count++;
//                                }
//                            }
//                            if(count == 0) {
//                                //System.out.println("fnish");
//                                flag = false;
//                            }
                        }
                        try {
                            SwingUtilities.invokeLater(new Runnable() {

                                public void run() {
                                    if(data != null && project.getStatus() == Project.RUN)
                                        Main.program.mainForm.pnChannel.setDataRow(popData().getURL(), view, 3);
                                    else
                                        Main.program.mainForm.pnChannel.setDataRow(null, view, 3);
                                }
                            });
                        } catch (Exception e) {
                        }
                    }
                    else {
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        return t;
    }

    public synchronized Data popData() {
        return data;
    }
}
